package com.codi.api.controller.wap;

import com.codi.api.validation.AccountValidation;
import com.codi.base.config.ConfigurationMgr;
import com.codi.base.log.annotation.Loggable;
import com.codi.base.util.RandomUtil;
import com.codi.base.util.StringUtil;
import com.codi.base.web.RequestUtils;
import com.codi.base.web.ResponseUtils;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.domain.Lookup;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.domain.UserSession;
import com.codi.bus.core.resultModel.LoginResult;
import com.codi.bus.core.resultModel.SMSSendResult;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.model.SMSParameter;
import com.codi.bus.core.service.model.UserModel;
import com.codi.bus.core.sys.service.AppUpdateService;
import com.codi.bus.exception.BaseException;
import com.codi.bus.util.VfCodeUsage;
import com.codi.goldlife.external.IntegralServiceApi;
import com.codi.goldlife.external.databean.ResultBean;
import com.codi.message.constant.ErrorConstant;
import com.codi.message.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/webacc")
public class WapAccountController {
    private static final Logger logger = LoggerFactory.getLogger(WapAccountController.class);

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "smsService")
    private SMSService smsService;

    @Resource(name = "bankService")
    private BankService bankService;

    @Resource(name = "queryService")
    private QueryService queryService;

    @Autowired
    private PaperInfoService paperInfoService;

    @Autowired
    private AppUpdateService auService;

    @Autowired
    private AccountValidation accountValidation;

    @Resource(name = "lookupService")
    private LookupService lookupService;

    @Autowired
    private ClientService clientService;

    @Autowired
    private IntegralServiceApi integralServiceApi;

    @Loggable
    @RequestMapping(value = "/sendvcode", method = RequestMethod.POST)
    public void sendVCode2(HttpServletRequest request, HttpServletResponse response, @RequestParam String mobile,
                           @RequestParam String applyNo,
                           @RequestParam(required = false) VfCodeUsage usage) throws BaseException {
        SMSSendResult result = null;
        // 验证输入
        String ip = RequestUtils.getIpAddr(request);
        if (usage == null) {
            usage = VfCodeUsage.Register;
        }

        // 获取短信发送控制配置
        List<Lookup> lookups = lookupService.getLookups(RuleConstant.RULE_LOOKUP_TYPE_SMSCONF);

        result = accountValidation.validateSendVCode(mobile, ip, applyNo, usage, lookups);
        if (result != null) {
            ResponseUtils.renderJson(request, response, result, true);
            return;
        }

        String verifyCode = RandomUtil.getNumRandom(6, true);

        // 限制在开发环境中使用
        Boolean mockSmsVerifyCode = ConfigurationMgr.getInstance()
            .getBoolean(GlobalConstant.CONFIG_MOCK_SMS_VERIFY_CODE, false);
        if (mockSmsVerifyCode) {
            verifyCode = "666666";
        }

        List<SMSParameter> list = new ArrayList<SMSParameter>();
        SMSParameter parameter = new SMSParameter();
        parameter.setKey(GlobalConstant.SMS_PLACEHOLDER_VCODE);
        parameter.setValue(verifyCode);
        list.add(parameter);

        result = smsService.generateSmsMessage(mobile, list);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }
        ResponseUtils.renderJson(request, response, result, true);
    }

    /**
     * web端用户注册
     */
    @Loggable
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public void register(HttpServletRequest request, HttpServletResponse response, User entity,
                         UserSession sessionEntity, String inviteMobile) throws BaseException {
        User user = userService.getUser(inviteMobile);

        if (user == null) {
            com.codi.bus.core.resultModel.BaseResult result = new com.codi.bus.core.resultModel.BaseResult();
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_MOBILE_INVALID);
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_MOBILE_INVALID, null));

            ResponseUtils.renderJson(request, response, result, true);
        }

        entity.setUserInviter(user.getUserId());

        // 验证输入
        LoginResult result = accountValidation.validateRegister(entity);

        if (result != null) {
            ResponseUtils.renderJson(request, response, result, true);
            return;
        }

        // 获取IP地址
        String ip = RequestUtils.getIpAddr(request);

        // 完成手机号注册
        entity.setUserState(User.USER_STATE_MOBILE);
        String token = userService.registerAccount(entity, sessionEntity, ip);
        result = new LoginResult();
        result.setSuccess(true);
        result.setToken(token);

        UserModel userModel = new UserModel();
        userModel.setIsOrg(false);
        result.setUser(userModel);
        logger.info("用户完成注册！！");
        logger.info("用户名：{}，手机号：{}", entity.getUserName(), entity.getUserMobile());
        if (entity.getUserInviter() != null) {
            User inviter = userService.getUser(entity.getUserInviter());
            logger.info("邀请人用户名：{}，邀请人手机号：{}", inviter.getUserName(), inviter.getUserMobile());
        }
        ResultBean resultBean = integralServiceApi.execIntegral(entity.getUserId().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_REGISTER, entity.getUserMobile());
        integralServiceApi.sendUserMsg(entity.getUserId().toString(), entity.getUserMobile(), "", GlobalConstant.INTEGRAL_CHANNEL_ID);
        if (resultBean.isSuccess()) {
            logger.info("用户注册积分添加成功！！");
            logger.info("用户名：{}，手机号：{}", entity.getUserName(), entity.getUserMobile());
            if (entity.getUserInviter() != null) {
                User inviter = userService.getUser(entity.getUserInviter());
                ResultBean resultBean1 = integralServiceApi.execIntegral(entity.getUserInviter().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_INVITE_REGISTER, inviter.getUserMobile());
                if (resultBean1.isSuccess()) {
                    logger.info("邀请用户注册积分添加成功！！");
                    logger.info("邀请人用户名：{}，手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                } else {
                    logger.info("邀请用户注册积分添加失败");
                    logger.info("失败原因：{}", resultBean1.getErrorMessage());
                    logger.info("邀请人用户名：{}，手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                }
            }
        } else {
            logger.info("用户注册积分添加失败");
            logger.info("用户名：{}，手机号：{}", entity.getUserName(), entity.getUserMobile());
            logger.info("失败原因：{}", resultBean.getErrorMessage());
        }
        ResponseUtils.renderJson(request, response, result, true);
    }

    @Loggable
    @RequestMapping(value = "/getInvitedUserinfos", method = RequestMethod.POST)
    public void getInvitedUserinfos(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "pageIndex") Integer pageIndex,
                                    @RequestParam(value = "pageSize") Integer pageSize,
                                    @RequestParam(value = "mobile") String mobile) throws BaseException {

        com.codi.bus.core.resultModel.BaseResult result = new com.codi.bus.core.resultModel.BaseResult();

        if (StringUtil.isEmpty(mobile)) {
            result.setErrorCode(ErrorConstant.ERROR_FIELD_NO_FIND);
            Map<String, String> map = new HashMap<>();
            map.put(ErrorConstant.PLACEHOLDER_FIELD_NO_FIND_FIELD, "手机号");
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_FIELD_NO_FIND, map));

            ResponseUtils.renderJson(request, response, result, true);
        }

        if (!StringUtil.isNumeric(mobile)) {
            result.setErrorCode(ErrorConstant.ERROR_MOBILE_INVALID);
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_MOBILE_INVALID, null));

            ResponseUtils.renderJson(request, response, result, true);
        }

        User user = userService.getUser(mobile);

        if (user == null) {
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_NO_USER_FIND, null));

            ResponseUtils.renderJson(request, response, result, true);
        }

        Long userId = user.getUserId();

        List<User> invitedUserInfos = userService.getInviteUserInfos(pageIndex, pageSize, userId);
        result.setResult(invitedUserInfos);

        ResponseUtils.renderJson(request, response, result, true);
    }
}
